﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB.YJKControls;
using YJKArchUtils.Utils;

namespace YJKRevitWallModule.WallModule
{
	public partial class DlgAxisToWall : System.Windows.Forms.Form
	{
		public DlgAxisToWall(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
			this.InitializeComponent();
			this.InitControls();
			this.ReadData();
		}

		public void InitControls()
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			this.m_basicWallTypes = new List<WallType>();
			this.m_curtainWallTypes = new List<WallType>();
			this.m_stackWallTypes = new List<WallType>();
			foreach (WallType wallType in Common.GetWallTypes(document))
			{
				WallType wallType2 = wallType as WallType;
				wallType2.get_Parameter(BuiltInParameter.FUNCTION_PARAM).AsInteger();
                if ((int)wallType2.Kind == 0)
				{
					this.m_basicWallTypes.Add(wallType2);
				}
                else if ((int)wallType2.Kind == 2)
				{
					this.m_stackWallTypes.Add(wallType2);
				}
                else if ((int)wallType2.Kind == 1)
				{
					this.m_curtainWallTypes.Add(wallType2);
				}
			}
			this.cmbOutFamily.Items.Add("基本墙");
			this.cmbInFamily.Items.Add("基本墙");
			this.cmbOutFamily.Items.Add("叠层墙");
			this.cmbInFamily.Items.Add("叠层墙");
			this.cmbOutFamily.Items.Add("幕墙");
			this.cmbInFamily.Items.Add("幕墙");
			this.cmbOutLevel.Items.Add("未约束");
			this.cmbInLevel.Items.Add("未约束");
			Level currentViewLevel = AssistFunc.GetCurrentViewLevel(document);
			foreach (Level level in Common.GetSortLevels(document, double.MinValue, double.MaxValue))
			{
				if (currentViewLevel != null)
				{
					if (currentViewLevel.Elevation < level.Elevation)
					{
						this.cmbOutLevel.Items.Add(level.Name);
						this.cmbInLevel.Items.Add(level.Name);
					}
				}
				else
				{
					this.cmbOutLevel.Items.Add(level.Name);
					this.cmbInLevel.Items.Add(level.Name);
				}
			}
			this.cmbOutFamily.SelectedIndex = 0;
			this.cmbInFamily.SelectedIndex = 0;
			if (this.cmbOutLevel.Items.Count > 0)
			{
				this.cmbOutLevel.SelectedIndex = 0;
			}
			if (this.cmbInLevel.Items.Count > 0)
			{
				this.cmbInLevel.SelectedIndex = 0;
			}
			this.m_ExternalWallOffset = "0";
			this.tbOffset.Text = this.m_ExternalWallOffset;
			this.m_OutWallHeight = "8000";
			this.tbOutWallHeight.Text = this.m_OutWallHeight;
			this.m_InsideWallHeight = "8000";
			this.tbInsideWallHeight.Text = this.m_InsideWallHeight;
		}

		public void GetWallData(ref WallData data)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			data.OutType = AssistFunc.GetWallTypeByName(document, this.cmbOutType.SelectedItem.ToString());
			data.InType = AssistFunc.GetWallTypeByName(document, this.cmbInType.SelectedItem.ToString());
			data.OutOffset = AssistFunc.mmToFeet((double)Convert.ToInt32(this.m_ExternalWallOffset));
			if (this.tbOutWallHeight.Enabled)
			{
				data.OutWallHeight = AssistFunc.mmToFeet((double)Convert.ToInt32(this.m_OutWallHeight));
			}
			else
			{
				data.OutWallHeight = 0.0;
			}
			if (this.tbInsideWallHeight.Enabled)
			{
				data.InsideWallHeight = AssistFunc.mmToFeet((double)Convert.ToInt32(this.m_InsideWallHeight));
			}
			else
			{
				data.InsideWallHeight = 0.0;
			}
			Level levelByName = AssistFunc.GetLevelByName(document, this.cmbOutLevel.SelectedItem.ToString());
			if (levelByName != null)
			{
				data.IdOutLevel = levelByName.Id;
			}
			else
			{
				data.IdOutLevel = ElementId.InvalidElementId;
			}
			Level levelByName2 = AssistFunc.GetLevelByName(document, this.cmbInLevel.SelectedItem.ToString());
			if (levelByName2 != null)
			{
				data.IdInLevel = levelByName2.Id;
				return;
			}
			data.IdInLevel = ElementId.InvalidElementId;
		}

		private void cmbOutFamily_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (this.cmbOutFamily.SelectedIndex == -1)
			{
				return;
			}
			string text = this.cmbOutFamily.SelectedItem.ToString();
			if ("叠层墙" == text || "幕墙" == text)
			{
				this.btnNewOutWallType.Enabled = false;
			}
			else
			{
				this.btnNewOutWallType.Enabled = true;
			}
			this.ResetTypeCombobox(text, true, this.cmbOutType);
			if (this.cmbOutType.Items.Count > 0)
			{
				this.cmbOutType.SelectedIndex = 0;
			}
		}

		private void cmbInFamily_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (this.cmbOutFamily.SelectedIndex == -1)
			{
				return;
			}
			string text = this.cmbInFamily.SelectedItem.ToString();
			if ("叠层墙" == text || "幕墙" == text)
			{
				this.btnNewInWallType.Enabled = false;
			}
			else
			{
				this.btnNewInWallType.Enabled = true;
			}
			this.ResetTypeCombobox(text, false, this.cmbInType);
			if (this.cmbInType.Items.Count > 0)
			{
				this.cmbInType.SelectedIndex = 0;
			}
		}

		private void ResetTypeCombobox(string familyType, bool isOutWall, System.Windows.Forms.ComboBox control)
		{
			control.Items.Clear();
			if (familyType.CompareTo("基本墙") == 0)
			{
				using (List<WallType>.Enumerator enumerator = this.m_basicWallTypes.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						WallType wallType = enumerator.Current;
						WallType walltype = wallType as WallType;
						this.InsertWallTypeToTypeCombobox(walltype, isOutWall, control);
					}
					return;
				}
			}
			if (familyType.CompareTo("叠层墙") == 0)
			{
				using (List<WallType>.Enumerator enumerator = this.m_stackWallTypes.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						WallType wallType2 = enumerator.Current;
						WallType walltype2 = wallType2 as WallType;
						this.InsertWallTypeToTypeCombobox(walltype2, isOutWall, control);
					}
					return;
				}
			}
			if (familyType.CompareTo("幕墙") == 0)
			{
				foreach (WallType wallType3 in this.m_curtainWallTypes)
				{
					WallType walltype3 = wallType3 as WallType;
					this.InsertWallTypeToTypeCombobox(walltype3, isOutWall, control);
				}
			}
		}

		private void InsertWallTypeToTypeCombobox(WallType walltype, bool isOutWall, System.Windows.Forms.ComboBox control)
		{
			if (isOutWall)
			{
				control.Items.Add(walltype.Name);
				return;
			}
			if (!isOutWall)
			{
				control.Items.Add(walltype.Name);
			}
		}

		private void SaveData()
		{
			FileStream fileStream = new FileStream(Path.GetTempPath() + "AxisToWallForm.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.cmbOutFamily.SelectedIndex);
			streamWriter.WriteLine(this.cmbOutType.SelectedIndex);
			streamWriter.WriteLine(this.cmbOutLevel.SelectedIndex);
			streamWriter.WriteLine(this.cmbInFamily.SelectedIndex);
			streamWriter.WriteLine(this.cmbInType.SelectedIndex);
			streamWriter.WriteLine(this.cmbInLevel.SelectedIndex);
			streamWriter.WriteLine(this.cbxBreak.Checked.ToString());
			streamWriter.WriteLine(base.Location.X);
			streamWriter.WriteLine(base.Location.Y);
			streamWriter.WriteLine(this.m_OutWallHeight);
			streamWriter.WriteLine(this.m_InsideWallHeight);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private bool ReadData()
		{
			string path = Path.GetTempPath() + "AxisToWallForm.dat";
			if (!File.Exists(path))
			{
				base.StartPosition = FormStartPosition.CenterScreen;
				return true;
			}
			base.StartPosition = FormStartPosition.Manual;
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			bool result;
			try
			{
				int num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbOutFamily.Items.Count)
				{
					this.cmbOutFamily.SelectedIndex = num;
				}
				num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbOutType.Items.Count)
				{
					this.cmbOutType.SelectedIndex = num;
				}
				num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbOutLevel.Items.Count)
				{
					this.cmbOutLevel.SelectedIndex = num;
				}
				num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbInFamily.Items.Count)
				{
					this.cmbInFamily.SelectedIndex = num;
				}
				num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbInType.Items.Count)
				{
					this.cmbInType.SelectedIndex = num;
				}
				num = Convert.ToInt32(streamReader.ReadLine());
				if (num > -1 && num <= this.cmbInLevel.Items.Count)
				{
					this.cmbInLevel.SelectedIndex = num;
				}
				string value = streamReader.ReadLine();
				bool @checked = false;
				bool.TryParse(value, out @checked);
				this.cbxBreak.Checked = @checked;
				int x = Convert.ToInt32(streamReader.ReadLine());
				int y = Convert.ToInt32(streamReader.ReadLine());
				base.Location = new System.Drawing.Point(x, y);
				this.m_OutWallHeight = streamReader.ReadLine();
				if (this.m_OutWallHeight.CompareTo("") == 0)
				{
					this.m_OutWallHeight = "8000";
				}
				this.tbOutWallHeight.Text = this.m_OutWallHeight;
				this.m_InsideWallHeight = streamReader.ReadLine();
				if (this.m_InsideWallHeight.CompareTo("") == 0)
				{
					this.m_InsideWallHeight = "8000";
				}
				this.tbInsideWallHeight.Text = this.m_InsideWallHeight;
				this.ChangeWallHeightState();
				streamReader.Close();
				fileStream.Close();
				result = true;
			}
			catch (Exception)
			{
				base.StartPosition = FormStartPosition.CenterScreen;
				streamReader.Close();
				fileStream.Close();
				result = true;
			}
			return result;
		}

		private void ChangeWallHeightState()
		{
			if (this.cmbOutLevel.SelectedItem != null && this.cmbOutLevel.SelectedItem.ToString().CompareTo("未约束") == 0)
			{
				this.tbOutWallHeight.Enabled = true;
			}
			else
			{
				this.tbOutWallHeight.Enabled = false;
			}
			if (this.cmbInLevel.SelectedItem != null && this.cmbInLevel.SelectedItem.ToString().CompareTo("未约束") == 0)
			{
				this.tbInsideWallHeight.Enabled = true;
				return;
			}
			this.tbInsideWallHeight.Enabled = false;
		}



		private void cmbOutType_SelectedIndexChanged(object sender, EventArgs e)
		{
			double num = AssistFunc.feetToMM(AssistFunc.GetWallTypeByName(this.m_Revit.Application.ActiveUIDocument.Document, this.cmbOutType.SelectedItem.ToString()).Width);
			this.lbWallThickness.Text = "墙厚 " + num.ToString() + " mm";
			this.tbOffset.Text = "0";
		}

		private void btnNewOutWallType_Click(object sender, EventArgs e)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			WallType wallTypeByName = AssistFunc.GetWallTypeByName(document, this.cmbOutType.SelectedItem.ToString());
			WallThicknessEditer wallThicknessEditer = new WallThicknessEditer(this.m_Revit);
			SubTransaction subTransaction = new SubTransaction(document);
			subTransaction.Start();
			WallType wallType = null;
			string text = "";
			if (!wallThicknessEditer.NewWallType(wallTypeByName, ref wallType, ref text))
			{
				subTransaction.RollBack();
				return;
			}
			subTransaction.Commit();
			string familyType = this.cmbOutFamily.SelectedItem.ToString();
			this.AddType(familyType, wallType);
			this.cmbOutType.Items.Add(wallType.Name);
			this.cmbOutType.Text = wallType.Name;
		}

		private void btnNewInWallType_Click(object sender, EventArgs e)
		{
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			WallType wallTypeByName = AssistFunc.GetWallTypeByName(document, this.cmbInType.SelectedItem.ToString());
			WallThicknessEditer wallThicknessEditer = new WallThicknessEditer(this.m_Revit);
			SubTransaction subTransaction = new SubTransaction(document);
			subTransaction.Start();
			WallType wallType = null;
			string text = "";
			if (!wallThicknessEditer.NewWallType(wallTypeByName, ref wallType, ref text))
			{
				if (text.CompareTo("") != 0)
				{
					YJKMessageBox.Show(text);
				}
				subTransaction.RollBack();
				return;
			}
			subTransaction.Commit();
			string familyType = this.cmbInFamily.SelectedItem.ToString();
			this.AddType(familyType, wallType);
			this.cmbInType.Items.Add(wallType.Name);
			this.cmbInType.Text = wallType.Name;
		}

		private void AddType(string familyType, WallType newWallType)
		{
			if (familyType.CompareTo("基本墙") == 0)
			{
				this.m_basicWallTypes.Add(newWallType);
				return;
			}
			if (familyType.CompareTo("叠层墙") == 0)
			{
				this.m_stackWallTypes.Add(newWallType);
				return;
			}
			if (familyType.CompareTo("幕墙") == 0)
			{
				this.m_curtainWallTypes.Add(newWallType);
			}
		}

		private void tbOffset_TextChanged(object sender, EventArgs e)
		{
			double num = AssistFunc.feetToMM(AssistFunc.GetWallTypeByName(this.m_Revit.Application.ActiveUIDocument.Document, this.cmbOutType.SelectedItem.ToString()).Width);
			try
			{
				if (this.tbOffset.Text.CompareTo("-") == 0)
				{
					return;
				}
				if (!Geometry.Lessthan_Or_Equal(Math.Abs((double)int.Parse(this.tbOffset.Text)), num / 2.0))
				{
					YJKMessageBox.Show("偏移范围不能超出半个墙厚.");
					this.tbOffset.Text = this.m_ExternalWallOffset;
					return;
				}
			}
			catch (FormatException)
			{
				YJKMessageBox.Show("请输入一个整数.");
				this.tbOffset.Text = this.m_ExternalWallOffset;
			}
			this.m_ExternalWallOffset = this.tbOffset.Text;
		}

		private void tbInsideWallHeight_TextChanged(object sender, EventArgs e)
		{
			try
			{
				if (Geometry.Lessthan_Or_Equal((double)int.Parse(this.tbInsideWallHeight.Text), 0.0))
				{
					YJKMessageBox.Show("请输入一个大于零的正整数.");
					this.tbOutWallHeight.Text = this.m_OutWallHeight;
					return;
				}
			}
			catch (FormatException)
			{
				YJKMessageBox.Show("请输入一个大于零的正整数.");
				this.tbInsideWallHeight.Text = this.m_InsideWallHeight;
			}
			this.m_InsideWallHeight = this.tbInsideWallHeight.Text;
		}

		private void tbOutWallHeight_TextChanged(object sender, EventArgs e)
		{
			try
			{
				if (Geometry.Lessthan_Or_Equal((double)int.Parse(this.tbOutWallHeight.Text), 0.0))
				{
					YJKMessageBox.Show("请输入一个大于零的正整数.");
					this.tbOutWallHeight.Text = this.m_OutWallHeight;
					return;
				}
			}
			catch (FormatException)
			{
				YJKMessageBox.Show("请输入一个大于零的正整数.");
				this.tbOutWallHeight.Text = this.m_OutWallHeight;
			}
			this.m_OutWallHeight = this.tbOutWallHeight.Text;
		}

		private void cmbOutLevel_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.ChangeWallHeightState();
		}

		private void cmbInLevel_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.ChangeWallHeightState();
		}

		public ExternalCommandData m_Revit;

		private List<WallType> m_basicWallTypes;

		private List<WallType> m_stackWallTypes;

		private List<WallType> m_curtainWallTypes;

		private string m_ExternalWallOffset = "0";

		private string m_OutWallHeight = "8000";

		private string m_InsideWallHeight = "8000";



        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

        private void DlgAxisToWall_MouseLeave(object sender, EventArgs e)
        {
            if (!base.ClientRectangle.Contains(base.PointToClient(Cursor.Position)))
            {
                int wMsg = 7;
                DlgAxisToWall.SendMessage(CmdWallCreateByAxis._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
                return;
            }
            base.Focus();
        }

        [DllImport("user32.dll")]
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        private void DlgAxisToWall_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.SaveData();
            int bVk = 27;
            int dwFlags = 0;
            int dwFlags2 = 2;
            DlgAxisToWall.keybd_event((byte)bVk, 0, dwFlags, 0);
            DlgAxisToWall.keybd_event((byte)bVk, 0, dwFlags2, 0);
        }
	}
}
